<template>
  <div id="EChartsVisits" ref="Charts"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts/core'
import { LineChart, LineSeriesOption } from 'echarts/charts'
import {
  TitleComponent,
  TitleComponentOption,
  GridComponent,
  GridComponentOption,
  ToolboxComponent,
  ToolboxComponentOption,
  TooltipComponent,
  TooltipComponentOption,
} from 'echarts/components'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onBeforeUnmount, onMounted, ref } from 'vue'

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<
  | LineSeriesOption
  | ToolboxComponentOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
>
// 注册必须的组件
echarts.use([
  GridComponent,
  UniversalTransition,
  CanvasRenderer,
  ToolboxComponent,
  LineChart,
  TitleComponent,
  TooltipComponent,
])
const props = defineProps<{
  HomeData: any[]
}>()

const VisitsData: Array<number> = []
const weeksData: Array<string> = [
  '周一',
  '周二',
  '周三',
  '周四',
  '周五',
  '周六',
  '周日',
]

let visits = 0
// 添加数据
for (let i = 0; i < props.HomeData[5].length; i++) {
  let [month, day] = (props.HomeData[5][i].createTime as string).split('/')

  let data = new Date(
    new Date().getFullYear() + '/' + (Number(month) + 1) + '/' + day
  )
  VisitsData[data.getDay() - 1 > 0 ? data.getDay() - 1 : 6] =
    props.HomeData[5][i].visits

  visits += props.HomeData[5][i].visits - 0
}
const option: ECOption = {
  // 标题
  title: {
    left: 'center',
    text: `周访问量(${visits})`,
    textStyle: {
      color: '#5470C6',
    },
  },
  // 保存图片
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  // 提示框
  tooltip: {
    trigger: 'axis',
  },
  //  表格主体
  grid: {
    width: '85%',
  },
  xAxis: {
    type: 'category',
    data: weeksData,
  },
  yAxis: {
    type: 'value',
  },
  // 数据
  series: [
    {
      name: '访问量',
      data: VisitsData,
      type: 'line',
      smooth: true, // 表示弯曲的
    },
  ],
}
const Charts = ref<HTMLDivElement>()

let myChart: echarts.ECharts | undefined
onMounted(() => {
  myChart = Charts.value && echarts.init(Charts.value)
  myChart && myChart.setOption(option)
  window.addEventListener('resize', resize)
})

function resize() {
  myChart && myChart.resize()
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', resize)
})
</script>
<style lang="scss" scoped>
#EChartsVisits {
  width: 100%;
  height: 400px;
  margin-top: 40px;
}
</style>
